<?php

declare(strict_types=1);
// +----------------------------------------------------------------------
// | swiftAdmin 极速开发框架 [基于WebMan开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2030 http://www.swiftadmin.net
// +----------------------------------------------------------------------
// | swiftAdmin.net High Speed Development Framework
// +----------------------------------------------------------------------
// | Author: meystack <coolsec@foxmail.com> Apache 2.0 License
// +----------------------------------------------------------------------
namespace app\admin\controller\system;


use app\AdminController;
use app\common\library\Ip2Region;
use app\common\model\system\Material as Materials;
use app\common\model\system\OrderMaterial;
use app\common\model\system\MaterialPrice;
use app\common\model\system\MaterialLog;
use app\common\model\system\Supplier;

use support\Response;
use system\Random;
use think\facade\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use Webman\Http\Request;

/**
 * 用户管理
 * Class User
 * @package app\admin\controller\system
 */
class Material extends AdminController
{
    // 初始化函数
    public function __construct()
    {
        parent::__construct();
        $this->model = new Materials();
    }

    public function pricecharts()
    {
        $post = \request()->all();
        $id = $post['id'] ?? 0;
        //12个月的日期
        $datelist = [];
        //获取本月时间戳
        $time = strtotime(date('Ym01'));
        for ($i = 0; $i < 12; $i++) {
            $strtotime = strtotime('-' . $i . ' month', $time);
            $datelist[] = [
                'date' =>  date('Ym', $strtotime),
                'frist' => date('Ym01', $strtotime),
                'last' => date('Ymt', $strtotime),
                'weight' => 0,
                'totals' => 0,
                'price' => 0,
                'oweight' => 0
            ];
        }
        //查询进货量 进货总价
        foreach ($datelist as $k => $list) {
            $prdate = (new MaterialPrice())->group('materialid')->field('sum(weight) as mweight,sum(totals) as mtotals')->whereBetween('dates', [$list['frist'], $list['last']])->where(['materialid' => $id])->find();
            $datelist[$k]['weight'] = (float)($prdate['mweight'] ?? 0);
            $datelist[$k]['totals'] = (float)($prdate['mtotals'] ?? 0);
            if ($datelist[$k]['weight'] > 0) {
                $datelist[$k]['price'] = floor($prdate['mtotals'] * 100 / $datelist[$k]['weight']) / 100;
            }
            $datelist[$k]['oweight'] = (new OrderMaterial())->group('materialid')
                ->whereBetween('ordersn', [$list['frist'], $list['last']])->where(['materialid' => $id])->value('sum(weights)') ?? 0;
        }
        return view('/system/material/pricecharts', ['datelist' => json_encode($datelist)]);
    }

    /**
     * 获取资源
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(): \support\Response
    {
        if (request()->isAjax()) {
            // 获取数据
            $post = \request()->all();
            $page = (int)input('page') ?? 1;
            $limit = (int)input('limit') ?? 10;
            // 生成查询条件
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', "%" . $post['title'] . "%"];
            }
            if (!empty($post['iswarn']) && $post['iswarn'] == 1) {
                $rmodel = $this->model->order("sku asc")->having('sku <= warn');
            } elseif (!empty($post['iswarn']) && $post['iswarn'] == 2) {
                $rmodel = $this->model->order("sku asc")->having('sku > warn');
            } else {
                $rmodel = $this->model->order("sku asc");
            }
            $lastmonth = date('Ym01', strtotime('-1 month')); //上个月初
            $tlastmonth = date('Ymt', strtotime('-1 month')); //上个月末
            $months = date('Ym01', time()); //本月
            $nextmonth = date('Ymt', time()); //这个月末
            $count = count($rmodel->where($where)->select());
            $page = ($count <= $limit) ? 1 : $page;
            $list = $rmodel->where($where)
                ->limit((int)$limit)->page((int)$page)
                ->select();
            foreach ($list as $item) {
                //进货数据
                $item['price'] = 0;
                $item['mtotals'] = 0;
                $item['mweight'] = 0;
                $item['tprice'] = 0;
                $item['ttotals'] = 0;
                $item['tweight'] = 0;
                $item['tweightout'] = 0;
                $item['mweightout'] = 0;
                $mprice = (new MaterialPrice())->group('materialid')
                    ->field('sum(weight) as mweight,sum(totals) as mtotals')
                    ->whereBetween('dates', [$months, $nextmonth])->where(['materialid' => $item['id'],])->find();
                if (!empty($mprice['mtotals']) && !empty($mprice['mweight'])) {
                    $item['price'] = floor($mprice['mtotals'] * 10000 / $mprice['mweight']) / 10000;
                }
                $item['mtotals'] = $mprice['mtotals'] ?? 0;
                $item['mweight'] = $mprice['mweight'] ?? 0;
                $tprice = (new MaterialPrice())->group('materialid')
                    ->field('sum(weight) as mweight,sum(totals) as mtotals')
                    ->whereBetween('dates', [$lastmonth, $tlastmonth])->where(['materialid' => $item['id'],])->find();
                if (!empty($tprice['mtotals']) && !empty($tprice['mweight'])) {
                    $item['tprice'] = floor($tprice['mtotals'] * 10000 / $tprice['mweight']) / 10000;
                }
                $item['ttotals'] = $tprice['mtotals'] ?? 0;
                $item['tweight'] = $tprice['mweight'] ?? 0;
                //本月出货数据
                $item['mweightout'] = (new OrderMaterial())->group('materialid')
                    ->whereBetween('ordersn', [$months, $nextmonth])->where(['materialid' => $item['id'],])->value('sum(weights)') ?? 0;
                //上月出货数据
                $item['tweightout'] = (new OrderMaterial())->group('materialid')
                    ->whereBetween('ordersn', [$lastmonth, $tlastmonth])->where(['materialid' => $item['id'],])->value('sum(weights)') ?? 0;
                //上月盈亏盘
                $time = date('Ym01');
                $yingkui = (new MaterialLog())->order('id desc')->where(['materialid' => $item['id']])->where('dates', '<=', $time)->value('afters') ?? 0;
                $item['yingkui'] =$yingkui;
            }
            return $this->success('查询成功', "", $list, $count);
        }
        return view('/system/material/index', []);
    }


    public function materialprice()
    {
        if (request()->isAjax()) {
            // 获取数据
            $post = \request()->all();
            $page = (int)input('page') ?? 1;
            $limit = (int)input('limit') ?? 10;
            // 生成查询条件
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['dates', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['materialid'])) {
                $where[] = ['materialid', '=', $post['materialid']];
            }
            if (!empty($post['supplierid'])) {
                $where[] = ['supplierid', '=', $post['supplierid']];
            }
            $count = (new MaterialPrice())->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = (new MaterialPrice())->where($where)->order("id desc")
                ->limit((int)$limit)->page((int)$page)
                ->select();
            foreach ($list as $item) {
                $item['materialtitle'] = $this->model->where('id', $item['materialid'])->value('title');
                $Supplier = (new Supplier())->where('id', $item['supplierid'])->find();
                $item['supplier'] = $Supplier['title'] ?? '无';
                $item['mobile'] = $Supplier['phone'] ?? '无';
                $item['images'] = json_decode($item['images'], true);
            }
            return $this->success('查询成功', "", $list, $count);
        }
        $material = $this->model->field('id,title')->select();
        $supplier = (new Supplier())->field('id,title,phone')->select();
        return view('/system/material/materialprice', ['material' => $material, 'supplier' => $supplier]);
    }

    public function materiallog()
    {
        if (request()->isAjax()) {
            // 获取数据
            $post = \request()->all();
            $page = (int)input('page') ?? 1;
            $limit = (int)input('limit') ?? 10;
            // 生成查询条件
            $where = array();
            if (!empty($post['materialid'])) {
                $where[] = ['materialid', '=', $post['materialid']];
            }
            $count = (new MaterialLog())->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = (new MaterialLog())->where($where)->order("id desc")
                ->limit((int)$limit)->page((int)$page)
                ->select();
            $arr = [
                1 => '入库变更',
                2 => '订单变更'
            ];
            foreach ($list as $item) {
                $item['materialtitle'] = $this->model->where('id', $item['materialid'])->value('title');
                $item['type_text'] = $arr[$item['type']] ?? '';
            }
            return $this->success('查询成功', "", $list, $count);
        }
        return view('/system/material/materiallog', []);
    }
    /**
     * 添加会员
     */
    public function add()
    {
        if (request()->isPost()) {
            $post = request()->post();
            $post = request_validate_rules($post, get_class($this->model));
            if (empty($post) || !is_array($post)) {
                return $this->error($post);
            }
            if ($this->model->create($post)) {
                return $this->success('添加成功！');
            }
            return $this->error('添加失败！');
        }
    }

    /**
     * 添加行情
     */
    public function fadd()
    {
        $materialid = input('materialid') ?? 0;
        $id = input('id') ?? 0;
        if (request()->isPost()) {
            $post = request()->post();
            $post = request_validate_rules($post, get_class($this->model));
            if (empty($post) || !is_array($post)) {
                return $this->error($post);
            }
            $post['album'] = $post['album'] ?? [];
            if (empty($post['album'])) {
                return $this->error('凭证图片不能为空');
            }
            foreach ($post['album'] as $value) {
                $post['images'][] = $value['src'];
            }
            $supplier = (new Supplier())->where('id', $post['supplierid'])->find();
            if (empty($supplier)) {
                return $this->error('供应商信息不存在');
            }
            $material =  $this->model->where('id', $post['materialid'])->find();
            if (empty($material)) {
                return $this->error('原材料信息不存在');
            }
            $post['images'] = json_encode($post['images']);
            $post['dates'] = (int)trim($post['dates']);
            $post['getdates'] = (int)trim($post['getdates']);
            $savedata = [
                'materialid' => $post['materialid'],
                'supplierid' => $post['supplierid'],
                'dates' => $post['dates'],
                'getdates' => $post['getdates'],
                'weight' => $post['weight'],
                'price' => $post['price'],
                'totals' => floor($post['weight'] * $post['price'] * 100) / 100,
                'images' => $post['images']
            ];
            if (!empty($post['id'])) {
                $materprice = (new MaterialPrice())->where('id', $post['id'])->find();
                if (empty($materprice)) {
                    return $this->error('记录已不存在');
                }
            }
            Db::startTrans();
            try {
                if (empty($post['id'])) {
                    (new MaterialPrice())->save($savedata);
                    (new MaterialLog())->MaterialSkuEdit(
                        $post['materialid'],
                        $post['weight'],
                        1,
                        $post['dates'],
                        '材料录入'
                    );
                } else {
                    (new MaterialPrice())->where('id', $post['id'])->update($savedata);
                    $money = $materprice['weight'] - $post['weight'];
                    (new MaterialLog())->MaterialSkuEdit(
                        $post['materialid'],
                        $money,
                        1,
                        $post['dates'],
                        '材料录入记录' . $post['id'] . '资料变更'
                    );
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->success('操作成功！');
        }
        //供应商
        $supplier = (new Supplier())->field('id,title,phone')->select();
        $material = '';
        if (!empty($materialid)) {
            $material = $this->model->where('id', $materialid)->value('title');
        }
        if (empty($id)) {
            $data = $this->getTableFields(new MaterialPrice());
        } else {
            $data = (new MaterialPrice())->find($id);
            if ($data) {
                $materialid = $data['materialid'];
                $material = $this->model->where('id', $data['materialid'])->value('title');
                $data['images'] = json_decode($data['images'], true);
                $albums = [];
                foreach ($data['images'] as $key => $value) {
                    $albums[$key] = [
                        'title' => '图片',
                        'src' => $value
                    ];
                }
                $data['album'] = $albums;
            } else {
                $data = $this->getTableFields(new MaterialPrice());
            }
        }
        return view('/system/material/fadd', [
            'data' => $data,
            'materialid' => $materialid,
            'supplier' => $supplier,
            'material' => $material
        ]);
    }

    /**
     * 添加会员
     */
    public function edit()
    {
        if (request()->isPost()) {
            $post = request()->post();
            $post = request_validate_rules($post, get_class($this->model));
            if (empty($post) || !is_array($post)) {
                return $this->error($post);
            }
            if ($this->model->update($post)) {
                return $this->success('添加成功！');
            }
            return $this->error('添加失败！');
        }
    }

    /**
     * 删除轮播图
     */
    public function del()
    {
        $id = input('id');
        if (!empty($id) && is_numeric($id)) {
            if ($this->model::destroy($id)) {
                return $this->success('删除成功！');
            }
        }
        return $this->error('删除失败，请检查您的参数！');
    }
}
